<template>
  <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '新增用户'" width="600px" @close="handleClose">
    <el-form ref="formRef" class="user-form" label-width="100px" :model="formData" :rules="rules">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="formData.mobile" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-select v-model="formData.sex" class="w-full" placeholder="请选择性别">
              <el-option label="男" value="1" />
              <el-option label="女" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属平台" prop="platformBelong">
            <el-select v-model="formData.platformBelong" class="w-full" placeholder="请选择所属平台">
              <el-option label="红有" value="1" />
              <el-option label="本系统" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="部门" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              check-strictly
              class="w-full"
              :data="departmentOptions"
              placeholder="请选择部门"
              :props="{ label: 'name', value: 'id', children: 'children' }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职务" prop="postsId">
            <el-select v-model="formData.postsId" class="w-full" multiple placeholder="请选择职务">
              <el-option v-for="item in postOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item class="switch-item" label="是否启用" prop="isEnabled">
            <el-switch v-model="formData.isEnabled" active-text="启用" inactive-text="禁用" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="switch-item" label="是否管理员" prop="isManager">
            <el-switch v-model="formData.isManager" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="描述" prop="desc">
        <el-input v-model="formData.desc" placeholder="请输入描述信息" :rows="3" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import Public from '/@/api/public'

const props = defineProps({
  isExternalUser: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['success', 'close'])

// 表单数据
const formData: any = reactive({
  id: null,
  openid: '',
  username: '',
  name: '',
  email: '',
  mobile: '',
  sex: '1',
  avatar: '',
  desc: '',
  isSuper: false,
  deptId: null,
  departments: {},
  roleId: null,
  isEnabled: true,
  isDepartmentCadres: false,
  isManager: false,
  platformBelong: '2',
  postsId: [],
})

const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const loading = ref(false)
const isEdit = ref(false)
const departmentOptions = ref<any[]>([])
const postOptions = ref<any[]>([])

// 表单验证规则
const rules = reactive<FormRules>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  mobile: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }],
  email: [{ pattern: /^\w+([+.-]\w+)*@\w+([.-]\w+)*\.\w+([.-]\w+)*$/, message: '请输入正确的邮箱格式', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  platformBelong: [{ required: true, message: '请选择所属平台', trigger: 'change' }],
})

// API URL根据是否为外部用户选择不同的端点
const apiUrl = computed(() => {
  return '/api/user'
})

// 加载部门数据
const loadDepartments = async () => {
  try {
    const response = await Public.getDetailApi({ url: '/api/department' })
    const data = response.data || response
    if (data && typeof data === 'object' && 'code' in data && data.code === 0 && 'result' in data) {
      departmentOptions.value = data.result
    }
  } catch (error) {
    console.error('加载部门数据失败:', error)
  }
}

// 加载职务数据
const loadPosts = async () => {
  try {
    const response = await Public.getDetailApi({ url: '/api/posts' })
    const data = response.data || response
    if (data && typeof data === 'object' && 'code' in data && data.code === 0 && 'result' in data) {
      postOptions.value = data.result
    }
  } catch (error) {
    console.error('加载职务数据失败:', error)
  }
}

// 初始化数据
onMounted(() => {
  loadDepartments()
  loadPosts()
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    openid: '',
    username: '',
    name: '',
    email: '',
    mobile: '',
    sex: '1',
    avatar: '',
    desc: '',
    isSuper: false,
    deptId: null,
    departments: {},
    roleId: null,
    isEnabled: true,
    isDepartmentCadres: false,
    isManager: false,
    platformBelong: '2',
    postsId: [],
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 处理职务数据，确保正确保存
        if (Array.isArray(formData.postsId) && formData.postsId.length > 0) {
          // 将选中的职务ID数组转为字符串
          formData.postsIdStr = formData.postsId.join(',')
        }

        const method = isEdit.value ? 'editApi' : 'addApi'
        const response = await Public[method]({
          url: apiUrl.value,
          data: formData,
          params: isEdit.value ? { id: formData.id } : undefined,
        })

        const data = response.data || response
        if (data && typeof data === 'object' && 'code' in data && data.code === 0) {
          ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
          dialogVisible.value = false
          emit('success')
        } else {
          ElMessage.error((data && typeof data === 'object' && 'message' in data ? data.message : '') || '操作失败')
        }
      } catch (error) {
        console.error('提交表单失败:', error)
        ElMessage.error('提交失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 打开弹窗 - 新增模式
const openAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 打开弹窗 - 编辑模式
const openEdit = (data: any) => {
  isEdit.value = true
  resetForm()

  // 处理职务数据，将字符串转为数组（如果需要）
  if (data.postsId && typeof data.postsId === 'string') {
    data.postsId = data.postsId
      .split(',')
      .map((id: string) => id.trim())
      .filter(Boolean)
  } else if (data.postsMiddle && Array.isArray(data.postsMiddle)) {
    // 从postsMiddle中提取职务ID
    data.postsId = data.postsMiddle.map((post: any) => {
      if (typeof post === 'object' && post.postsId) {
        return post.postsId
      }
      return post
    })
  }

  // 确保platformBelong是字符串类型
  if (data.platformBelong !== undefined && data.platformBelong !== null) {
    data.platformBelong = String(data.platformBelong)
  }

  // 填充表单数据
  Object.assign(formData, data)
  dialogVisible.value = true
}

// 关闭弹窗
const handleClose = () => {
  resetForm()
  emit('close')
}

// 对外暴露方法
defineExpose({
  openAdd,
  openEdit,
})
</script>

<style scoped>
.w-full {
  width: 100%;
}

.user-form {
  padding: 0 10px;
}

.user-form .el-row {
  margin-bottom: 10px;
}

.switch-item {
  display: flex;
  align-items: center;
}

.dialog-footer {
  padding-top: 10px;
  text-align: right;
}
</style>
